package com.haoshuang.zhouzhoubang.ui.page.study.exam

import android.content.Context
import android.os.Bundle
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityExamBinding
import com.haoshuang.zhouzhoubang.model.bean.ExamQuestionBean
import com.haoshuang.zhouzhoubang.model.bean.QuestionBean
import com.haoshuang.zhouzhoubang.ui.page.study.exam.submit.SubmitAnswerActivity
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.SpannableStringUtils
import com.mufeng.libs.utils.ktx.convertInt
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.vertical
import java.util.Timer
import java.util.TimerTask

/**
 *  开始考试页面
 */
class ExamActivity : BaseVMActivity<ExamViewModel, ActivityExamBinding>() {

    companion object {
        fun launch(context: Context, type: Int = 1, articleId: Int = -1) {
            context.startPage<ExamActivity>(
                "type" to type,
                "article_id" to articleId
            )
        }
    }

    private var type = 1

    // 文章id
    private var articleId = -1

    // 第几题
    private var position = 0

    // 题目数量
    private var answerSize = 0

    // 考试倒计时
    private var timer = Timer()
    private var timerTask: TimerTask? = null
    private var seconds = 0

    // 题目选项
    private val data = arrayListOf<QuestionBean>()
    private val adapter = ExamQuestionsAdapter(data)

    // 当前选中的题目
    private var examination: ExamQuestionBean.ExamQuestionItem? = null

    // 题目数据
    private var examQuestion: ExamQuestionBean? = null

    private var rightNum = 0
    /**积分*/
    private var integral = 0

    override fun initIntent() {
        type = intent.getIntExtra("type", 1)
        articleId = intent.getIntExtra("article_id", -1)
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.titleBar.title = "考试"
        binding.titleBar.leftImageView().click { finish() }

        updateTitleNumber()

        binding.rvAnswer.vertical().adapter = adapter
        adapter.setOnItemClick { view, position, item ->
            if (item?.is_Check == 0) {
                if ((examination?.question_type ?: 0) in intArrayOf(1, 3)) {
                    data.forEach {
                        if (it.id == item.id) {
                            it.is_Check = 1
                        } else {
                            it.is_Check = 0
                        }
                    }
                } else {
                    item.is_Check = 1
                }
            }
            adapter.notifyDataSetChanged()
        }

        // 下一题 / 交卷
        binding.tvNext.clickWithTrigger {
            val list = data.filter { it.is_Check == 1 }
            if (list.isEmpty()) {
                toast("请选择答案")
                return@clickWithTrigger
            }
            val answers = list.joinToString(","){it.title}
            checkAnswers(answers)
            if (position == examQuestion?.list?.size) {
                timerTask?.cancel()
                timer.cancel()
                // 正确率
                val rate = rightNum * 100 / (examQuestion?.list?.size ?: 0)
                val errorNum = (examQuestion?.total ?: 0) - rightNum
                vm.submitExamResult(
                    rate.toString(),
                    integral.toString(),
                    type.toString(),
                    articleId,
                    rightNum.toString(),
                    errorNum.toString()
                )
            } else {
                examination = examQuestion?.list?.get(position++)
                setData(examination!!)
                updateTitleNumber()
            }
        }

        timerTask = object : TimerTask() {
            override fun run() {
                seconds++
            }
        }
        timer.schedule(timerTask, 1000, 1000)
    }

    /**
     * 更新题号的UI
     */
    private fun updateTitleNumber() {
        binding.tvNumberAnswers.text = SpannableStringUtils(mActivity, "${position}/${answerSize}")
            .first("/${answerSize}").textColor(R.color.c_33)
    }

    override fun initData() {
        vm.getTrainExamQuestion(articleId)
    }

    override fun startObserve() {
        vm.getTrainExamQuestionData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                examQuestion = it?.data
                if (examQuestion != null) {
                    answerSize = examQuestion?.total ?: 0
                    updateTitleNumber()
                    if (examQuestion?.list?.isNotEmpty() == true) {
                        examination = examQuestion?.list?.get(position++)
                        updateTitleNumber()
                        setData(examination!!)
                        type = examQuestion?.list?.get(0)?.type ?: 1
                    }
                }
            }
        }

        vm.submitExamResultData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                startPageForResult<SubmitAnswerActivity>("total" to examQuestion?.total,
                    "right" to rightNum,
                    "integral" to integral,
                    "time" to seconds,
                    "article_id" to articleId){code, data ->
                    if (code == 200){
                        val isFinish = data?.getBooleanExtra("isFinish", false)
                        if (isFinish == true){
                            finish()
                        }else{
                            rightNum = 0
                            integral = 0
                            seconds = 0
                            position = 0
                            vm.getTrainExamQuestion(articleId)
                        }
                    }
                }
            }
        }
    }

    private fun setData(examination: ExamQuestionBean.ExamQuestionItem) {
        if (position == examQuestion?.list?.size) {
            binding.tvNext.text = "交卷"
        } else {
            binding.tvNext.text = "下一题"
        }
        data.clear()
        if (examination.question_type == 3) {
            data.add(QuestionBean(1,"正确", "A", 0))
            data.add(QuestionBean(2,"错误", "B", 0))
        } else {
            data.add(QuestionBean(1,examination.answer1, "A", 0))
            data.add(QuestionBean(2,examination.answer2, "B", 0))
            data.add(QuestionBean(3,examination.answer3, "C", 0))
            data.add(QuestionBean(4,examination.answer4, "D", 0))
        }
        adapter.notifyDataSetChanged()
        val title = if (examination.question_type == 2) {
            SpannableStringUtils(mActivity, "【多选】${examination.title}").first("【多选】")
                .textColor(R.color.c_3b76c2)
        } else {
            SpannableStringUtils(mActivity, "【单选】${examination.title}").first("【单选】")
                .textColor(R.color.c_3b76c2)
        }
        binding.tvExamTitle.text = title
    }

    /**
     * 验证答案
     */
    private fun checkAnswers(answer: String) {
        if (answer == examination?.true_answer) {
            rightNum++
            integral += examination?.integral.convertInt()
        }
    }

}